$(document).ready(function () {
    //获取父菜单列表
    getParentMenuList();

});
//数据表格

let parentMenuJson;
layui.use(['table','form'], function() {
    let table = layui.table
        , form = layui.form;

    form.on('submit(createMenu)',function () {
        createMenu();
    });


    table.render({
        elem: '#menusList'
        , method: "post"
        , url: '/menusList'
        , toolbar: '#topTools' //开启头部工具栏，并为其绑定左侧模板
        , title: '菜单列表'
        , totalRow: true
        , request: {
            pageName: 'curPage',
            limitName: 'pageSize'
        }, parseData: function (res) {
            return {
                "code": res.code == 200 ? 0 : -1,
                "msg": "",
                "count": res.data.count,
                "data": res.data.data
            }
        }
        , cols: [
            [
                {
                    field: 'id',
                    title: 'ID',
                    width: 80,
                    fixed: 'left',
                    unresize: true,
                    sort: true
                }
                , {field: 'parentId', title: '父菜单', width: 120, edit: 'text'}
                , {field: 'title', title: '菜单名', width: 150, edit: 'text'}
                , {
                field: 'createTime',
                title: '创建日期',
                width: 200,
                templet: "<div>{{layui.util.toDateString(d.createTime, 'yyyy-MM-dd HH:mm:ss')}}</div>"
            }
                , {field: 'url', title: 'URL', width: 200, edit: 'text'}
                , {fixed: 'right', title: '操作', toolbar: '#menuOperator', width: 200}
            ]]
        , page: true
        , done: function (res, curr, count) {
            // console.log(res, curr, count);
            let menu = "{";
            $.each(res.data, function (index, item) {
                menu += '"' + item.id + '":' + '"' + item.title + '"' + ","
            })
            menu = menu.replace(/(,$)/g, '') + "}";
            let json = JSON.parse(menu);
            // console.log(parentMenuJson);
            // console.log(json);
            $("[data-field='parentId']").children().each(function () {
                let parentId = $(this).text();
                // console.log(parentId)
                if (parentId === "0") {
                    $(this).text("无父级菜单");
                } else {
                    $(this).text(parentMenuJson[parentId]);
                }

            })
        }
    });
    let type ;
    // $("input[name='']").val();
    form.on('radio(menuType)', function (obj) {
        type = obj.value ;
    });
    //监听头部工具事件
    table.on('toolbar(menusList)', function (obj) {
        switch (obj.event) {
            case 'createNewMenu' :
                createMenuModel();
                break;
            case 'searchMenu':
                searchMenu();
                break;
        }

        function searchMenu() {
            let key = $("#searchMenuName").val();
            table.reload('menusList', {
                method:"post"
                ,where: {
                    'title': key,
                    'parentId':type
                    // 'parentId': type
                }
                , page: {
                    curr: 1
                }
            });
            form.val("categoryForm",{
                "searchMenuName":key,
                "menuType":type
            });
        }
    });

    //监听行工具事件
    table.on('tool(menusList)', function (obj) {
        let data = obj.data;
        if (obj.event === 'del') {
            layer.confirm('确定删除该分类吗？', function (index) {
                obj.del();
                $.ajax({
                    url: "/delMenu",
                    method: "post",
                    data: JSON.stringify(data),
                    dataType: "json",
                    contentType: "application/json;charset=utf-8;",
                    success: function (data) {
                        if (data == "1") {
                            alert("删除成功！");
                            location.reload()
                        } else {
                            alert("删除失败！");
                        }
                    }
                });
                layer.close(index);
            });
        } else if (obj.event === "edit") {
            // console.log(data)
            $.ajax({
                url: "/editMenu",
                method: "post",
                charset: "UTF-8",
                dataType: "json",
                contentType: "application/json;charset=utf-8;",
                data: JSON.stringify(data),
                success: function (data) {
                    if (data == "1") {
                        alert("修改菜单成功");
                        cleanerText();
                        location.reload();
                        layer.close(layer.index);
                    } else {
                        alert("修改菜单失败");
                        cleanerText();
                        layer.close(layer.index);
                    }
                }
            });
        }
    });


    function createMenuModel() {
        layui.use(['layer'], function () {
            let layer = layui.layer, $ = layui.$;
            layer.open({
                type: 1,
                anim: 4,
                area: ['auto', 'auto'],
                title: '新增菜单',
                shadeClose: false,
                content: $('#createMenu')
            });
        });
    }



})
function cleanerText() {
    $("input[name='title']").val("");
    $("input[name='url']").val("");
}

function getParentMenuList() {
    $.ajax({
        url: "/getAllParentMenu",
        method: "get",
        charset: "UTF-8",
        async: false,
        success: function (res) {
            let parentMenuSelect = $("#parentMenuSelect");
            parentMenuSelect.empty();
            parentMenuSelect.append("<option value= '0' >无父级菜单</option>");
            let parentMenuList = res.data;
            let parentMenu="{";
            $.each(parentMenuList, function (index, value) {
                parentMenu+='"' + value.id + '":' + '"' + value.title + '"' + ",";

                if (value.id != 3) {
                    parentMenuSelect.append("<option value='" + value.id + "'" + ">" + value.title + "</option>");
                }

            });
            parentMenu = parentMenu.replace(/(,$)/g, '') + "}";
            parentMenuJson = JSON.parse(parentMenu);

        }

    })
}


//创建菜单
function createMenu() {
    let title = $("input[name='title']").val();
    let url = $("input[name='url']").val();
    let parentId = $("#parentMenuSelect").val();
    let menuJson = {"title": title, "url": url, "parentId": parentId};
    $.ajax({
        url: "/createNewMenu",
        method: "post",
        charset: "UTF-8",
        dataType: "json",
        contentType: "application/json;charset=utf-8;",
        data: JSON.stringify(menuJson),
        success: function (data) {
            if (data == "1") {
                alert("新增菜单成功");
                cleanerText();
                location.reload();
                layer.close(layer.index);
            } else {
                alert("新增菜单失败");
                cleanerText();
                layer.close(layer.index);
            }
        }
    });
}